package com.ibs.hadoop.spring.mybatis.comm;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;

import org.apache.ibatis.session.RowBounds;

public class Pagination<T> implements Serializable {

	
	private static final long serialVersionUID = 1L;
    
	
	private long total = 900000000L;
	
	private int pagesize;
	
	private List<T> list = Collections.emptyList();
	
	private int offset;
	
	private int limit;
	
	private int page;
	
	public Pagination() {
		this(1, 15);
	}
	
	public Pagination(int page) {
		this(page, 15);
	}
	
	public Pagination(int page, int limit) {
		setPage(page);
		setLimit(limit);
	}
	
	public Pagination(RowBounds rowBounds) {
		this.limit = rowBounds.getLimit();
		this.offset = rowBounds.getOffset();
		this.page = offset / limit + 1;
	}
	
	public void setPage(int page) {
		if (page < 0) {
			page = 1;
		}
		this.page = page;
		onInit();
	}
	
	public void setLimit(int limit) {
		if (limit < 1) {
			limit = 15;
		}
		this.limit = limit;
		onInit();
	}
	
	protected void onInit() {
		offset = (page - 1) * limit;
	}
	
	protected void onSetRowsize() {
		pagesize = (int) (total / limit);
		if (total % limit > 0) {
			pagesize ++;
		}
		if (page > pagesize) {
			page = pagesize;
			onInit();
		}
	}
	
	protected void onSetList() {
		if (list == null || list.isEmpty()) {
			total = 0;
			page = 1;
			offset = 0;
		}
	}

	public long getTotal() {
		return total;
	}

	public void setTotal(long rowsize) {
		this.total = rowsize;
		onSetRowsize();
	}

	public int getPagesize() {
		return pagesize;
	}

	public List<T> getList() {
		return list;
	}
	
	public void setList(List<T> list) {
		this.list = list;
		onSetList();
	}

	public int getOffset() {
		return offset;
	}

	public int getLimit() {
		return limit;
	}

	public int getPage() {
		return page;
	}
	
	public RowBounds newRowBounds() {
		return new RowBounds(getOffset(), getLimit());
	}
}
